package com.xxl.shoppingapp.ui.main;


import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;


import com.xxl.baselib.baseui.widget.MainTabHost;
import com.xxl.shoppingapp.R;
import com.xxl.shoppingapp.base.BaseFragment;

import butterknife.Bind;

/**
 * Title: MainFragment.java
 * Description:
 * Copyright (c) 版权所有请勿抄袭 2018
 * Created DateTime: 2018/4/10 14:33
 * Created by xuelianx.
 */
public class MainFragment extends BaseFragment implements TabHost.OnTabChangeListener {

    private static MainFragment instance;

    public synchronized static MainFragment getInstance() {
        if (instance == null) {
            instance = new MainFragment();
        }
        return instance;
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_main;
    }

    @Bind(android.R.id.tabhost)
    MainTabHost tabHost;

    @Override
    protected void initView(View view) {
        super.initView(view);
    }

    @Override
    protected void needToDo() {
        super.needToDo();
        iniTabHost();
    }

    private void iniTabHost() {
        tabHost.setup(activity(), getChildFragmentManager(), R.id.main_content);
        tabHost.getTabWidget().setDividerDrawable(android.R.color.transparent);//去掉分割线
        initTabs();
        tabHost.setCurrentTab(0);
        tabHost.setOnTabChangedListener(this);
    }

    private void initTabs() {
        MainTab[] tabs = MainTab.values();
        for (MainTab mainTab : tabs) {
            TabHost.TabSpec tab = tabHost.newTabSpec(getString(mainTab.getResName()));
            View indicator = LayoutInflater.from(activity()).inflate(R.layout.layout_tab_indicator, null);
            TextView title = (TextView) indicator.findViewById(R.id.tab_indicator_title);
            ImageView icon = (ImageView) indicator.findViewById(R.id.tab_indicator_icon);
            title.setText(getResources().getString(mainTab.getResName()));
            icon.setImageResource(mainTab.getResIcon());
            tab.setIndicator(indicator);
            tab.setContent(new TabHost.TabContentFactory() {
                @Override
                public View createTabContent(String tag) {
                    return new View(activity());
                }
            });
            tabHost.addTab(tab, mainTab.getClz(), null);
        }
    }

    @Override
    public void onTabChanged(String tabId) {
        final int size = tabHost.getTabWidget().getTabCount();
        for (int i = 0; i < size; i++) {
            View v = tabHost.getTabWidget().getChildTabViewAt(i);
            if (i == tabHost.getCurrentTab()) {
                v.setSelected(true);
            } else {
                v.setSelected(false);
            }
        }
    }
}
